package s63.kong.shop.modules.security;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import s63.kong.shop.modules.token.ITokenService;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenFilter extends OncePerRequestFilter {
    @Resource
    private ITokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response
            , FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)){
            //从redis中找回用户
            LoginUser loginUser = tokenService.getLoginUser(token);
            //存储到spring security全局上下文对象中，以便鉴权使用
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(loginUser.getUsername(),null,loginUser.getAuthorities()));
        }
        filterChain.doFilter(request,response);
    }
}
